import wepy from 'wepy'
export default class extends wepy.mixin {
  data = {
    // 收货地址
    address: null,
    cart: []
  }
  methods = {
    // 选择收货地址
    async chooseAddress() {
      const res = await wepy.chooseAddress().catch(err => err)
      if (res.errMsg !== 'chooseAddress:ok') {
        return
      }
      this.address = res
      this.$apply()
      wepy.setStorageSync('address', this.address);
    },
    // 获取用户登陆信息
    async getUserInfo(userInfo) {
      // 获取用户信息
      if (userInfo.detail.errMsg !== 'getUserInfo:ok') {
        return
      }
      console.log(userInfo)

      // 微信登陆
      const loginRes = await wepy.login()
      console.log(loginRes)
      if (loginRes.errMsg !== 'login:ok') {
        return wepy.baseToast('微信登陆失败')
      }

      // 登陆请求参数
      const loginParams = {
        code: loginRes.code,
        encryptedData: userInfo.detail.encryptedData,
        iv: userInfo.detail.iv,
        rawData: userInfo.detail.rawData,
        signature: userInfo.detail.signature
      }

      const {data: res} = await wepy.post('/users/wxlogin', loginParams)
      console.log(res)
      if (res.meta.status !== 200) {
        return wepy.baseToast('微信登录失败！')
      }
    }
  }

  computed = {
    isHaveAddress() {
      if (!this.address) {
        return true
      }
      return false
    },
    addressStr() {
      const address = this.address
      if (!address) {
        return null
      }
      return address.provinceName + address.cityName + address.countyName + address.detailInfo
    }
  }

  onLoad() {
    this.address = wepy.getStorageSync('address') || null
    this.cart = this.$parent.globalData.cart.filter(x => x.isCheck) || []

  }
}